#pragma once
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <functional>

#include "Common.hpp"
#include "Log.hpp"
#include "Inetaddr.hpp"

using namespace LogModule;

const int defaultsockfd = -1;
const int backlog = 5;

class TCPServer
{
public:
    TCPServer(uint16_t port) : _port(port), _listensockfd(defaultsockfd), _isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建监听套接字
        int _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success";

        InetAddr local(_port);
        // 2.监听套接字bind源IP+源端口
        int n = bind(_listensockfd, local.NetAddrPtr(), local.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";

        // 3.监听
        n = listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success";
    }

    void Service(int socketfd, InetAddr &peer)
    {
        while (true)
        {
            char buffer[1024];
            ssize_t n = read(socketfd, &buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                std::string ecoh_string = "echo#";
                ecoh_string += buffer;
                write(socketfd, ecoh_string.c_str(), ecoh_string.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::DEBUG) << peer.StringAddr() << "退出了";
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "读取异常";
                break;
            }
        }
        close(socketfd);
    }

    void Run()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 1.accept获取连接套接字
            sockaddr_in peer;
            socklen_t len;
            memset(&peer, 0, sizeof(peer));
            int sockfd = accept(_listensockfd, CONV(peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "accept error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "accept success";

            // 2.处理连接信息
            InetAddr addr(peer);
            Service(sockfd, addr);
        }
        _isrunning = false;
    }

    ~TCPServer()
    {
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
};